/*
 *
 *
 *
 */
package com.cms.template.directive;

import cn.hutool.core.collection.CollectionUtil;
import com.cms.entity.Nav;
import com.cms.entity.Site;
import com.cms.service.NavService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 模板指令 - 根导航列表
 */
@Component
public class NavRootListDirective extends BaseDirective {

    @Autowired
    private NavService navService;

    /**
     * 变量名称
     */
    private static final String VARIABLE_NAME = "navs";

    @SuppressWarnings({"unchecked", "rawtypes"})
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        Site currentSite = getCurrentSite();
        Integer siteId = currentSite.getId();
        Integer start = getStart(params);
        Integer count = getCount(params);
        List<Nav> navs = navService.findRoots(start, count, siteId);
        //查询是否有子导航
        for (Nav nav : navs) {
            List<Nav> navList = navService.findChildren(nav.getId(), false, start, count, siteId);
            if (CollectionUtil.isNotEmpty(navList)) {
                nav.setHasChildren(true);
            } else {
                nav.setHasChildren(false);
            }
        }
        setLocalVariable(VARIABLE_NAME, navs, env, body);
    }
}